package com.guyu.plugin.mybatis.listener;

import cn.hutool.core.util.ObjectUtil;
import com.guyu.common.core.entity.KeyValue;
import com.guyu.plugin.mybatis.entity.BaseDO;
import com.guyu.plugin.mybatis.entity.BaseUserDO;
import com.guyu.plugin.mybatis.helper.MybatisFlexHelper;
import com.mybatisflex.annotation.InsertListener;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Objects;

@Slf4j
public class BaseDOInsertListener implements InsertListener {
    @Override
    public void onInsert(Object entity) {
        if (entity instanceof BaseDO baseDO) {
            LocalDateTime current = ObjectUtil.defaultIfNull(baseDO.getCreateTime(), LocalDateTime.now());
            baseDO.setCreateTime(current);
            baseDO.setUpdateTime(current);
        }
        if (entity instanceof BaseUserDO baseDO) {
            //如果已设置过则使用设置的值，否则去获取当前登录用户信息
            Long createUserId = baseDO.getCreateBy();
            String createUserName = baseDO.getCreatorName();
            if (Objects.isNull(createUserId)) {
                //监听用户信息
                FlexUserListener flexUserListener = MybatisFlexHelper.getUserListener();
                if (Objects.isNull(flexUserListener)) {
                    log.warn("自动注入警告 => 用户未登录");
                    return;
                }
                KeyValue<Long, String> user = flexUserListener.getUser();
                if (Objects.nonNull(user)) {
                    createUserId = user.getKey();
                    createUserName = user.getValue();
                }
            }
            createUserId = ObjectUtil.defaultIfNull(createUserId, 0L);
            createUserName = ObjectUtil.defaultIfNull(createUserName, "");

            baseDO.setCreateBy(createUserId);
            baseDO.setCreatorName(createUserName);
            baseDO.setUpdateBy(createUserId);
            baseDO.setUpdaterName(createUserName);
        }
    }
}
